<template>
  <div class="income-pending">
    <div class="page-header">
      <h2>待结算收入</h2>
      <p>管理平台待结算的收入记录</p>
    </div>

    <el-card class="table-card">
      <el-table :data="pendingIncomes" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="taskTitle" label="任务标题" min-width="150" />
        <el-table-column prop="taskStatus" label="任务状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getTaskStatusTagType(row.taskStatus)">
              {{ getTaskStatusText(row.taskStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publisherName" label="发布者" width="100" />
        <el-table-column prop="accepterName" label="接取者" width="100" />
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="{ row }">
            <span class="amount">¥{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="platformRate" label="平台费率" width="100">
          <template #default="{ row }">
            <span v-if="row.platformRate">{{ row.platformRate }}%</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="settleIncome(row.id)"
              :loading="settlingIds.includes(row.id)"
              :disabled="row.taskStatus !== 3"
            >
              {{ row.taskStatus === 3 ? '结算' : '任务未完成' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPendingIncome, settleIncome as settleIncomeApi } from '../../utils/api'

const loading = ref(false)
const pendingIncomes = ref([])
const settlingIds = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取待结算收入列表
const loadPendingIncomes = async () => {
  try {
    loading.value = true
    console.log('开始获取待结算收入...')
    const response = await getPendingIncome()
    console.log('待结算收入API响应:', response)
    if (response.data && response.data.code === 200) {
      pendingIncomes.value = response.data.data || []
      total.value = response.data.data ? response.data.data.length : 0
      console.log('待结算收入数据:', pendingIncomes.value)
    } else {
      console.error('API返回错误:', response.data?.message)
      ElMessage.error(response.data?.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取待结算收入失败:', error)
    ElMessage.error('获取数据失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 结算收入
const settleIncome = async (incomeId) => {
  try {
    // 找到对应的收入记录
    const income = pendingIncomes.value.find(item => item.id === incomeId)
    if (!income) {
      ElMessage.error('收入记录不存在')
      return
    }
    
    // 检查任务状态
    if (income.taskStatus !== 3) {
      ElMessage.error('只有已完成的任务才能结算收入')
      return
    }
    
    await ElMessageBox.confirm('确定要结算这笔收入吗？', '确认结算', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    settlingIds.value.push(incomeId)
    const response = await settleIncomeApi(incomeId)
    
    if (response.data && response.data.code === 200) {
      ElMessage.success('结算成功')
      await loadPendingIncomes() // 重新加载数据
    } else {
      ElMessage.error(response.data?.message || '结算失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('结算收入失败:', error)
      ElMessage.error('结算失败')
    }
  } finally {
    settlingIds.value = settlingIds.value.filter(id => id !== incomeId)
  }
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    1: '发布费',
    2: '完成费',
    3: '平台费'
  }
  return typeMap[type] || '未知'
}

// 获取类型标签样式
const getTypeTagType = (type) => {
  const typeMap = {
    1: 'info',
    2: 'success',
    3: 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取任务状态文本
const getTaskStatusText = (status) => {
  const statusMap = {
    0: '待解决',
    1: '已关闭',
    2: '解决中',
    3: '已完成',
    '-1': '任务不存在'
  }
  return statusMap[status] || '未知'
}

// 获取任务状态标签样式
const getTaskStatusTagType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'danger',
    2: 'warning',
    3: 'success',
    '-1': 'danger'
  }
  return typeMap[status] || 'info'
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadPendingIncomes()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadPendingIncomes()
}

onMounted(() => {
  loadPendingIncomes()
})
</script>

<style scoped>
.income-pending {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.table-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.amount {
  color: #67c23a;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
